<?php
/**
 * @file : articlevote.php
 * @date : 2015-02-04 10:08:16
 */
namespace haibao\cms\data;

use \haibao\cms\model\filter\ArticleVote as ArticleVoteFilter;

class ArticleVote extends \haibao\cms\data\BaseMysql{

    public function __construct(){
        parent::__construct('\haibao\cms\model\data\ArticleVote');
    }
    
    /**
     * 给文章关联图片投票
     */
    public function voteArticleImage($articleId, $voteId, $pid){
        $this->query('update ArticleVoteProperty set VoteNum=VoteNum+1 where Id=%s and ArticleVoteId=%s limit 1', array(
            $pid, $voteId
        ));
        $this->query('update ArticleVote set VoteNum = (select sum(VoteNum) from `ArticleVoteProperty` where ArticleVoteId=%s) where Id=%s and ArticleId=%s limit 1', array(
            $voteId, $voteId, $articleId
        ));
    }

    /**
     * 明星库首页 判断当前用户是否已投当前明星猜猜猜
     */
    public function checkUserVote($userId,$guessId){
    	$sql = 'select * from ArticleVoteByUser where CreateBy = %s and ArticleVoteId = %s limit 1';
    	return $this->query($sql,array($userId,$guessId))->fetch_assoc();
    }
    
	/**
	 * 添加文章投票
	 * @param : object \haibao\cms\model\data\ArticleVote
	 */
	public function addArticleVote($articleVoteModel){
	
		self::beginTranscation ();
		try {
	 		$this->add ( $articleVoteModel );
			$this->addArticleVoteRelationTable ( $articleVoteModel );
		} catch ( \Exception $e ) {
			$this->rollback ();
			throw $e;
		}
		$this->endTranscation ();
		if (\haibao\classlibrary\cms\Config::getConfig(\haibao\classlibrary\cms\Config::SYNC_OLD)) {
			
			// 老记录
			$this->addOldArticleVote($articleVoteModel);
		}
	}
	
	/**
	 * 修改文章投票
	 * @param : object \haibao\cms\model\data\ArticleVote
	 */
	public function editArticleVote($articleVoteModel){
		
	self::beginTranscation ();
		try {
			$this->updateById($articleVoteModel->Id,
				array(
					ArticleVoteFilter::CONDITION_FIELD_NAME_IS_MULTIPLE => $articleVoteModel->IsMultiple,
					ArticleVoteFilter::CONDITION_FIELD_NAME_PRIMARY_TITLE => $articleVoteModel->PrimaryTitle,
					ArticleVoteFilter::CONDITION_FIELD_NAME_INTERACTION_TYPE => $articleVoteModel->InteractionType
				)
			);
			$votePropertyData = new ArticleVoteProperty;
			$votePropertyData->editArticleVoteProperty($articleVoteModel);
			if($voteArticleTag = $articleVoteModel->VoteArticleTag){
				$sql = "delete from ArticleTag where ArticleId =%s AND TagId=%s";
				$this->query($sql,array($voteArticleTag->ArticleId,$voteArticleTag->TagId));
				$this->add($voteArticleTag);
			}
		} catch ( \Exception $e ) {
			$this->rollback ();
			throw $e;
		}
		$this->endTranscation ();
		if (\haibao\classlibrary\cms\Config::getConfig(\haibao\classlibrary\cms\Config::SYNC_OLD)) {
			// 老记录
			$this->editOldArticleVote($articleVoteModel);
		}
	}
	
	/**
	 * 添加文章投票附加信息(文章属性)
	 * @param : object \haibao\cms\model\data\ArticleVote
	 */
	private function addArticleVoteRelationTable($articleVoteModel){
		
		if($articleVoteModel->ArticleVoteProperty){

			foreach($articleVoteModel->ArticleVoteProperty as $voteProperty){
				$voteProperty->ArticleVoteId = $articleVoteModel->Id;
				$this->add($voteProperty);
			}
		}
		if($voteArticleTag = $articleVoteModel->VoteArticleTag){
			$sql = "delete from ArticleTag where ArticleId =%s AND TagId=%s";
			$this->query($sql,array($voteArticleTag->ArticleId,$voteArticleTag->TagId));
			$this->add($voteArticleTag);
		}
	}
	
	/**
	 * 根据文章投票ID删除投票信息
	 * @param : int $articleVoteId
	 * @param : int $articleId
	 */
	public function deleteArticleVoteByVoteId($articleVoteId,$articleId){
		
		self::beginTranscation ();
		try {
			
			$this->removeById($articleVoteId);
			$sql = 'delete from `ArticleVoteProperty` where ArticleVoteId=%s';
			$this->query($sql,array($articleVoteId));
			
			$sql = 'delete from `ArticleVoteByUser` where ArticleVoteId=%s';
			$this->query($sql,array($articleVoteId));
		
		} catch ( \Exception $e ) {
			$this->rollback ();
			throw $e;
		}
		$this->endTranscation ();
		if (\haibao\classlibrary\cms\Config::getConfig(\haibao\classlibrary\cms\Config::SYNC_OLD)) {
			// 老记录
			$this->deleteOldArticleVote($articleId);
		}
		
	}
	
	/**
	 * 当前文章是否有投票，如果有返回'热力互动'标签
	 * @param 文章id $articleId
	 */
	public function getVoteTag($articleId){
		$voteTag = array();
		$sql="select count(*) as count from ArticleVote where ArticleId = %s ";
		$result = $this->query($sql,array($articleId))->fetch_assoc();
		if($result['count']){
			$voteTag= array('Id'=>'2713','TagName'=>'热力互动','TopId'=>'6013');
		}
		return $voteTag;
	}
	
	/**
	 * 同步添加老数据文章投票
	 * @param : object \haibao\cms\model\data\ArticleVote
	 */
	private function addOldArticleVote($articleVoteModel){
		
		// 获取文章关联ID
		$this->initNewDB();
		$sql = 'select OldPrimaryKey from DataMigrationMap where TableName = %s and PrimaryKey =%s';
		$result = $this->query($sql,array('Article',$articleVoteModel->ArticleId))->fetch_assoc();
		$oldArticleId = $result['OldPrimaryKey'];
		if($oldArticleId){

			$this->initOldDB();
			$sql = 'insert into `vote_newvote` (article_id,count,multiple,primarytitle,Interactiontype) values (%s,%s,%s,%s,%s)';
			$this->query($sql,array($oldArticleId,0,$articleVoteModel->IsMultiple,$articleVoteModel->PrimaryTitle,$articleVoteModel->InteractionType));
			$oldVoteId = $this->getDb()->insert_id;
			if($oldVoteId){
				$vote_tag_id = 2713;
				$sql = "DELETE from rel_doc_tag where document_id=%s and tag_id=%s";
				$this->query($sql,array($oldArticleId,$vote_tag_id));
				$time = time();
				$sql = "insert into rel_doc_tag (document_id,tag_id,istpl,suser,lastmodified) values(%s, %s,0,%s,%s)";
				$this->query($sql,array($oldArticleId,$vote_tag_id,'admin',$time));
			}
			foreach($articleVoteModel->ArticleVoteProperty as $property){
				
				$valArr = array();
				$this->initOldDB();
				$sql = 'insert into `vote_newvoteoption` (vote_id,title,result,`order`) values (%s,%s,%s,%s)';
				array_push($valArr, $oldVoteId);
				array_push($valArr, $property->Title);
				array_push($valArr, $property->Des);
				array_push($valArr, $property->OrderNum);
				$this->query($sql,$valArr);
				$insertId =  $this->getDb()->insert_id;

				$this->initNewDB();
				$sql = "insert into DataMigrationMap (TableName,PrimaryKey,OldPrimaryKey) ";
				$sql .= "values('".$property->getTableName()."',".$property->Id.",".$insertId.")";
				$this->query($sql);
			}
			$sql = "insert into DataMigrationMap (TableName,PrimaryKey,OldPrimaryKey) ";
			$sql .= "values('".$articleVoteModel->getTableName()."',".$articleVoteModel->Id.",".$oldVoteId.")";
			$this->query($sql);
		}
	}
	/**
	 * 同步更新老数据文章投票
	 * @param : object \haibao\cms\model\data\ArticleVote
	 */
	private function editOldArticleVote($articleVoteModel){
		// 获取文章关联ID
		$this->initNewDB();
		$sql = 'select OldPrimaryKey from DataMigrationMap where TableName = %s and PrimaryKey =%s';
		$result = $this->query($sql,array('Article',$articleVoteModel->ArticleId))->fetch_assoc();
		$oldArticleId = $result['OldPrimaryKey'];
		
		if($oldArticleId){
			
			
			$this->initOldDB();
			$sql = 'update `vote_newvote` set multiple=%s,primarytitle=%s,Interactiontype=%s where article_id=%s';
			$this->query($sql,array($articleVoteModel->IsMultiple,$articleVoteModel->PrimaryTitle,$articleVoteModel->InteractionType,$oldArticleId));
			$vote_tag_id = 2713;
			$sql = "DELETE from rel_doc_tag where document_id=%s and tag_id=%s";
			$this->query($sql,array($oldArticleId,$vote_tag_id));
			$time = time();
			$sql = "insert into rel_doc_tag (document_id,tag_id,istpl,suser,lastmodified) values(%s, %s,0,%s,%s)";
			$this->query($sql,array($oldArticleId,$vote_tag_id,'admin',$time));
			$votePropertyIds = $oldVotePropertyIds = $properties = array();
			
			foreach($articleVoteModel->ArticleVoteProperty as $property){
				$votePropertyIds[] = $property->Id;
				$properties[$property->Id] = $property;
			}
			
			if($votePropertyIds){
				$this->initNewDB();
				$sql = 'select OldPrimaryKey,PrimaryKey from DataMigrationMap where TableName = %s and PrimaryKey in ('.implode(',',$votePropertyIds).')';
				$result = $this->query($sql,array('ArticleVoteProperty'));
				while($result->fetch_assoc()){
					$oldVotePropertyIds[$result->getData('PrimaryKey')] = $result->getData('OldPrimaryKey');
				}

				$this->initOldDB();
				foreach($properties as $key=>$property){
					if(isset($oldVotePropertyIds[$key])){
						$sql = 'update `vote_newvoteoption` set title=%s,result=%s,`order`=%s where id=%s';
						$this->query($sql,array($property->Title,$property->Des,$property->OrderNum,$oldVotePropertyIds[$key]));
					}
				}
				
				$sql = 'select id from `vote_newvote` where article_id = %s';
				$result = $this->query($sql,array($oldArticleId))->fetch_assoc();
				$oldVoteId = $result['id'];
				if($oldVoteId){
					$sql = 'delete from `vote_newvoteoption` where vote_id=%s and id not in ('.implode(',',$oldVotePropertyIds).')';
					$this->query($sql,array($oldVoteId));
				
					/* $this->initNewDB();
					 $sql = 'delete from `DataMigrationMap` where TableName=%s and OldPrimaryKey in ()'; */
					if($articleVoteModel->ArticleVotePropertyNew)
					foreach($articleVoteModel->ArticleVotePropertyNew as $property){
							
						$valArr = array();
						$this->initOldDB();
						$sql = 'insert into `vote_newvoteoption` (vote_id,title,result,`order`) values (%s,%s,%s,%s)';
						array_push($valArr, $oldVoteId);
						array_push($valArr, $property->Title);
						array_push($valArr, $property->Des);
						array_push($valArr, $property->OrderNum);
						$this->query($sql,$valArr);
						$insertId =  $this->getDb()->insert_id;
							
						$this->initNewDB();
						$sql = "insert into DataMigrationMap (TableName,PrimaryKey,OldPrimaryKey) ";
						$sql .= "values('".$property->getTableName()."',".$property->Id.",".$insertId.")";
						$this->query($sql);
					}
				}
			
			}else{
				$this->initOldDB();
				$sql = 'select id from `vote_newvote` where article_id = %s';
				$result = $this->query($sql,array($oldArticleId))->fetch_assoc();
				$oldVoteId = $result['id'];
				if($oldVoteId){
					
					$sql = 'delete from `vote_newvoteoption` where vote_id=%s';
					$this->query($sql,array($oldVoteId));
					
					if($articleVoteModel->ArticleVotePropertyNew)
					foreach($articleVoteModel->ArticleVotePropertyNew as $property){
							
						$valArr = array();
						$this->initOldDB();
						$sql = 'insert into `vote_newvoteoption` (vote_id,title,result,`order`) values (%s,%s,%s,%s)';
						array_push($valArr, $oldVoteId);
						array_push($valArr, $property->Title);
						array_push($valArr, $property->Des);
						array_push($valArr, $property->OrderNum);
						$this->query($sql,$valArr);
						$insertId =  $this->getDb()->insert_id;
							
						$this->initNewDB();
						$sql = "insert into DataMigrationMap (TableName,PrimaryKey,OldPrimaryKey) ";
						$sql .= "values('".$property->getTableName()."',".$property->Id.",".$insertId.")";
						$this->query($sql);
					}
				}
			}
		}
	}
	
	/**
	 * 同步删除老数据
	 * @param : int $articleVoteId
	 */
	private function deleteOldArticleVote($articleId){
		$this->initNewDB();
		$sql = 'select OldPrimaryKey from DataMigrationMap where TableName = %s and PrimaryKey =%s';
		$result = $this->query($sql,array('Article',$articleId))->fetch_assoc();
		$oldArticleId = $result['OldPrimaryKey'];
		
		$this->initOldDB();
		$sql = 'select id from `vote_newvote` where article_id = %s';
		$result = $this->query($sql,array($oldArticleId));
		$oldVoteIds = array();
		while($result->fetch_assoc()){
			
			$oldVoteIds[] = $result->getData('id');
		}
		if($oldVoteIds){
			$sql = 'delete from `vote_newvote` where article_id = %s';
			$this->query($sql,array($oldArticleId));
			$sql = 'delete from `vote_newvoteoption` where vote_id in (%s)';
			$this->query($sql,array(implode(',',$oldVoteIds)));
		}
		
	}
	private function initNewDB() {
		$this->setConfig( \haibao\classlibrary\cms\Config::CLASSLIBRARY_CONFIG_MYSQL_HAIBAO_CMS );
		return $this;
	}
	private function initOldDB() {
		$this->setConfig( \haibao\classlibrary\cms\Config::CLASSLIBRARY_CONFIG_MYSQL_HAIBAO_ARTICLE );
		return $this;
	}
}
